package com.example.petstore.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.petstore.common.CommonResponse;
import com.example.petstore.domain.Admin;
import com.example.petstore.domain.Message;
import com.example.petstore.domain.MessageLog;
import com.example.petstore.domain.User;
import com.example.petstore.mapper.MessageLogMapper;
import com.example.petstore.mapper.MessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service("messageService")
public class MessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MessageLogMapper messageLogMapper;

    //获取消息的用户id列表，按时间从晚到早排序
    public List<String>  getDistinctUserIDsAndUsernamesOrderByDateDesc() {
        return messageMapper.selectDistinctUserIDsAndUsernamesOrderByDateDesc();
    }

    //插入聊天消息
    public CommonResponse<Message> insertChat(Message message) {

        int result = messageMapper.insert(message);
        if(result > 0) {
            return CommonResponse.creatForSuccess(message);//判断是否更新成功
        }
        else {
            return CommonResponse.creatForError();
        }

    }



    //根据userid查找message表中的条目，按时间从早到晚排列
    public List<Message> selectMessagesByUserIdOrderByTime(String userId) {
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Message::getUsername, userId).orderByAsc(Message::getCreateTime);
        return messageMapper.selectList(queryWrapper);
    }
    public int countMessagesForAdmin(String username, String adminname) {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        QueryWrapper<MessageLog> queryWrapper1 = new QueryWrapper<>();
        LocalDateTime adminLeftTime = LocalDateTime.now();
        queryWrapper1.eq("adminname" ,adminname)
                .eq("username",username);
       MessageLog result = messageLogMapper.selectOne(queryWrapper1);
        if (result != null) {
            System.out.println(result);
           adminLeftTime = result.getAdminLeftTime();
            System.out.println("adminLeftTime"+ adminLeftTime);
        }
        queryWrapper.eq("username", username)
                .ge("createtime", adminLeftTime );

        Long count = messageMapper.selectCount(queryWrapper);
        return count != null ? count.intValue() : 0;
    }


    public int countMessagesForUser(String username) {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        QueryWrapper<MessageLog> queryWrapper1 = new QueryWrapper<>();
        LocalDateTime userLeftTime = LocalDateTime.now();
        queryWrapper.isNull("adminname")
                .eq("username", username);
        MessageLog result = messageLogMapper.selectOne(queryWrapper1);
        if (result != null) {
            userLeftTime = result.getUserLeftTime();
        }
        queryWrapper.eq("username", username)
                .ge("createtime", userLeftTime );

        Long count = messageMapper.selectCount(queryWrapper);
        return count != null ? count.intValue() : 0;
    }

    public CommonResponse<MessageLog> updateMessageLogForAdmin(String username, String adminname,MessageLog messageLog) {
        QueryWrapper<MessageLog> queryWrapper = new QueryWrapper<>();
        int rowsAffected;
        queryWrapper.eq("adminname" ,adminname)
                .eq("username",username);
        MessageLog result = messageLogMapper.selectOne(queryWrapper);
        if(result == null){
            rowsAffected = messageLogMapper.insert(messageLog);
        }else {
            UpdateWrapper<MessageLog> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("adminname", adminname)
                    .eq("username",username);
            rowsAffected = messageLogMapper.update(messageLog, updateWrapper);
        }

        if(rowsAffected > 0) {
            return CommonResponse.creatForSuccess(messageLog);//判断是否更新成功
        }
        else {
            return CommonResponse.creatForError();
        }
    }

    public CommonResponse<MessageLog> updateMessageLogForUser(String username,MessageLog messageLog) {
        QueryWrapper<MessageLog> queryWrapper = new QueryWrapper<>();
        int rowsAffected;
        queryWrapper.isNull("adminname")
                .eq("username",username);
        MessageLog result = messageLogMapper.selectOne(queryWrapper);
        if(result == null){
            rowsAffected = messageLogMapper.insert(messageLog);
        }else {
            UpdateWrapper<MessageLog> updateWrapper = new UpdateWrapper<>();
            updateWrapper.isNull("adminname")
                    .eq("username",username);
            rowsAffected = messageLogMapper.update(messageLog, updateWrapper);
        }

        if(rowsAffected > 0) {
            return CommonResponse.creatForSuccess(messageLog);//判断是否更新成功
        }
        else {
            return CommonResponse.creatForError();
        }
    }

    public CommonResponse getMessagesByUser(String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        List<Message> messages = messageMapper.selectList(queryWrapper);
        return CommonResponse.creatForSuccess(messages);
    }
}
